/**
 * 通用方法封装处理
 */
var public_vars = public_vars || {};

(function ($) {
    public_vars.$body = $('body');
    public_vars.$pageLoading = public_vars.$body.find('.page-loading-overlay');

    $.extend({
        // 通用方法封装处理
        common: {
            rootPath: function () {
                var strFullPath = window.document.location.href,
                    strPath = window.document.location.pathname;
                var pos = strFullPath.indexOf(strPath);
                var prePath = strFullPath.substring(0, pos);
                var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
                return prePath + postPath;
            },
            language: function () {
                var selectLan = "en";
                var languageType = $.common.cookie.get('Language');
                if (!languageType) {
                    languageType = "zh-CN";
                }

                return languageType;
            },
            autoHeight: function (ele) {
                var offsetH = ele.get(0).offsetHeight;
                // var docH = $(document).height(),
                //     winH = $(window).height(),
                //     screenH = screen.height;

                return $(window).height() - offsetH - 175;
            },
            iframe: {
                get: function(iframeName, top) {
                    var p;
                    if ($.common.isEmpty(top) || top == true) {
                        p = window.top;
                    } else {
                        p = parent;
                    }
                    if (p.window.frames[iframeName]) {
                        return p.window.frames[iframeName];
                    }

                    return p;
                }
            },
            // 判断字符串是否为空
            isEmpty: function (value) {
                if (value == null || this.trim(value) == '' || value == 'undefined') {
                    return true;
                }
                return false;
            },
            // 判断一个字符串是否为非空串
            isNotEmpty: function (value) {
                return !$.common.isEmpty(value);
            },
            // 空对象转字符串
            nullToStr: function(value) {
                if ($.common.isEmpty(value)) {
                    return '';
                }
                return value;
            },
            // 是否显示数据 为空默认为显示
            visible: function (value) {
                if ($.common.isEmpty(value) || value == true) {
                    return true;
                }
                return false;
            },
            // 空格截取
            trim: function (value) {
                if (value == null) {
                    return '';
                }
                return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, '');
            },
            // 指定随机数返回
            random: function (min, max) {
                return Math.floor((Math.random() * max) + min);
            },
            startWith: function(value, start) {
                var reg = new RegExp('^' + start);
                return reg.test(value)
            },
            endWith: function(value, end) {
                var reg = new RegExp(end + '$');
                return reg.test(value)
            },
            // 数组去重
            uniqueFn: function(array) {
                var result = [];
                var hashObj = {};
                for (var i = 0; i < array.length; i++) {
                    if (!hashObj[array[i]]) {
                        hashObj[array[i]] = true;
                        result.push(array[i]);
                    }
                }
                return result;
            },
            cookie: {
                get: function (name) {
                    var arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
                    if(arr = document.cookie.match(reg))
                        return unescape(arr[2]);
                    else
                        return null;
                },
                set: function (name, value, days) {
                    days = days || 30;
                    var exp = new Date();
                    exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
                    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toUTCString();
                },
                remove: function (name) {
                    var exp = new Date();
                    exp.setTime(exp.getTime() - 1);
                    var c_val = $.common.cookie.get(name);
                    if(c_val != null)
                        document.cookie = name + '=' + c_val + ';expires=' + exp.toUTCString();
                }
            },
            // 回显数据字典
            dictLabel: function (datas, value, size) {
                if (!size || size < 1) {
                    size = 1;
                }

                var actions = [];
                var temp = '';
                $.each(datas, function(index, dict) {
                    temp = ',' + dict.dictValue + ',';
                    if (temp.indexOf(',' + value + ',') > -1) {
                        actions.push("<span class='badge badge-" + dict.cssClass + "'>" + dict.dictLabel + "</span>  ");
                        if (size-- == 0) {
                            return false;
                        }
                    }
                });
                return actions.join('  ');
            },
            // 回显数据字典
            configLabel: function (datas, value, size) {
                if (!size || size < 1) {
                    size = 1;
                }

                var actions = [];
                var temp = '';
                $.each(datas, function(index, config) {
                    temp = ',' + config.value + ',';
                    if (temp.indexOf(',' + value + ',') > -1) {
                        actions.push("<span class='badge badge-primary'>" + config.value + "</span>  ");
                        if (size-- == 0) {
                            return false;
                        }
                    }
                });
                return actions.join('  ');
            },
            // 比较两个字符串（大小写不敏感）
            equalsIgnoreCase: function (str, target) {
                return String(str).toUpperCase() === String(target).toUpperCase();
            },
            // 将字符串按指定字符分割
            split: function (str, sep, maxLen) {
                if ($.common.isEmpty(str)) {
                    return null;
                }
                var value = String(str).split(sep);
                return maxLen ? value.slice(0, maxLen - 1) : value;
            },
            // 字符串格式化(%s )
            printf: function (str) {
                var args = arguments, flag = true, i = 1;
                str = str.replace(/%s/g, function () {
                    var arg = args[i++];
                    if (typeof arg === 'undefined') {
                        flag = false;
                        return '';
                    }
                    return arg;
                });
                return flag ? str : '';
            },
            // 页面渲染处理
            render: {
                // 文字超出长度长度处理
                ellipsis: function (data, length) {
                    var length =  $.common.isEmpty(length) ? 15 : length;
                    var data = $.common.nullToStr(data);
                    var show = data;
                    if (data.length > length) {
                        show = data.substring(0, length) + '...';
                    }
                    return $.common.printf('<span style="cursor: pointer" title=\'%s\' ondblclick=\'$.common.render.toggleText(this, ' + length + ')\'>%s</span>', data, show);
                },
                toggleText: function (element, length) {
                    length =  $.common.isEmpty(length) ? 15 : length;
                    var title = $(element).attr('title');
                    var info = $(element).text();
                    if(title == info) {
                        if (title.length > length) {
                            $(element).text(title.substring(0, length) + '...');
                        }
                    } else {
                        $(element).text(title);
                    }
                },
                // 密码切换显示
                togglePassword: function (data) {
                    var show = '*****';
                    return $.common.printf('<span p=\'%s\' ondblclick=\'$.common.render.togglePwd(this)\'>%s</span>', data, show);
                },
                togglePwd: function (element) {
                    var v = $(element).attr('p');
                    var info = $(element).text();
                    if (v == info) {
                        $(element).text('*****');
                    } else {
                        $(element).text(v);
                    }
                },
                toggleBadge: function (data, sep) {
                    if ($.common.isEmpty(data)) {
                        return '';
                    }
                    var value = String(data).split(sep);
                    var actions = [];
                    $.each(value, function(index, text) {
                        actions.push("<span class='badge badge-default m-b-xs'>" + text + "</span>  ");
                    });
                    return actions.join('  ');
                },
                // 文字超出指定长度浮动提示
                tooltip: function (data, length) {
                    var length = $.common.isEmpty(length) ? 15 : length;
                    var data = $.common.nullToStr(data);
                    var show = data;
                    if (show.length > length) {
                        show = data.substring(0, length) + '...';
                        return $.common.printf('<a href=\'#\' class=\'tooltip-show\' data-toggle=\'tooltip\' title=\'%s\'>%s</a>', data, show);
                    } else {
                        return show;
                    }
                },
                // 转义html
                htmlEscape: function(html) {
                    html.replace(/[<>"&]/g, function(match, pos, originalText) {
                        switch(match){
                            case "<": return "&lt;";
                            case ">":return "&gt;";
                            case "&":return "&amp;";
                            case "\"":return "&quot;";
                        }
                    });
                },
                showLayer: function(fn, title) {
                    return '<a class="td-a" herf="#" onclick=' + fn + '>' + title + '</a>';
                },
                open: function(title, url) {
                    $.modal.lay.openHtml({
                        title: title,
                        content: url
                    });
                },
                select: function(elementName, names, values, selected) {
                    var html = '<div><select class="form-control selectpicker" name="' + elementName + '">';
                    var options = [];
                    if (names.length == values.length) {
                        $.each(names, function(index, name) {
                            options.push('<option value="' + values[index] + '" ' + (selected == values[index] ? 'selected' : '') + '>' + name + '</option>');
                        });
                    }
                    html += options.join('');
                    html += '</select></div>';
                    return html;
                },
                convertFileSize: function (limit) {
                    var size = "";
                    if( limit < 0.1 * 1024 ){ //如果小于0.1KB转化成B
                        size = limit.toFixed(2) + "B";
                    }else if(limit < 0.1 * 1024 * 1024 ){//如果小于0.1MB转化成KB
                        size = (limit / 1024).toFixed(2) + "KB";
                    }else if(limit < 0.1 * 1024 * 1024 * 1024){ //如果小于0.1GB转化成MB
                        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
                    }else{ //其他转化成GB
                        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
                    }

                    var sizestr = size + "";
                    var len = sizestr.indexOf("\.");
                    var dec = sizestr.substr(len + 1, 2);
                    if(dec == "00"){//当小数点后为00时 去掉小数部分
                        return sizestr.substring(0,len) + sizestr.substr(len + 3,2);
                    }
                    return sizestr;
                }
            },
            // 下拉按钮切换
            dropdown: function (value) {
                var actions = [];
                actions.push('<div class="btn-group opera">');
                actions.push('<button type="button" class="btn btn-outline dropdown-toggle" data-toggle="dropdown" aria-expanded="false">');
                actions.push('<i class="fa fa-cog"></i>&nbsp;<span class="fa fa-chevron-down"></span></button>');
                actions.push('<ul class="dropdown-menu">');
                actions.push(value.replace(/<a/g,"<li><a").replace(/<\/a>/g,"</a></li>"));
                actions.push('</ul>');
                actions.push('</div>');

                return actions.join('');
            },
            // 通用下载文件
            download: function (url) {
                var download_frame = window.parent.document.getElementById('downloadFrame');
                if (download_frame != null) {
                    window.parent.document.body.removeChild(download_frame);
                }

                var iframe = window.parent.document.createElement("iframe");
                iframe.setAttribute('id', 'downloadFrame');
                window.parent.document.body.appendChild(iframe);
                download_frame = window.parent.document.getElementById('downloadFrame');
                download_frame.src = url;
                download_frame.style.display = 'none';
            }
        },
        xpathFormat: {
            extractNumber: function (str) {
                var match = /\d+/.exec(str);
                return match ? parseInt(match[0]) : str;
            },
            extractFloat: function (str) {
                var match = /(\d+(\.\d+)?)/.exec(str);
                return match ? parseFloat(match[0]) : str;
            },
            extractSizeText: function (str) {
                var sizeUnit = ['B|bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var sizeUnitSpare = ['B|bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
                var sizeUnitRegx = sizeUnit.join('|');
                var sizeUnitSpareRegx = sizeUnitSpare.join('|');
                var match = new RegExp(`(\\d+(\\.\\d+)?)(&nbsp;| )*(${sizeUnitRegx}|${sizeUnitSpareRegx})`, 'gi').exec(str);
                return match ? match[0] : str;
            },
            // 提取文本
            extractTextByNode: function (node) {
                if (node) {
                    if (Array.isArray(node)) {
                        if (node.length > 0) {
                            return node[0].textContent.trim();
                        }
                    } else {
                        return node.textContent.trim();
                    }
                }
                return null;
            },
            // 提取分辨率
            extractResolution: function (name) {
                var regx = {
                    '4K': '2160|4k',
                    '2K': '1440|2k',
                    '1080P': '1920|1080',
                    '720P': '1280|720'
                };
                $.each(regx, function(key, val) {
                    if (new RegExp(regx[key], 'i').test(name)) {
                        return key;
                    }
                });
            },
            // 提取磁力链接
            extractMagnet: function (url) {
                if (url) {
                    // 如果是磁力链 直接返回
                    if (/^(magnet:\?xt=urn:btih:)/.test(url)) {
                        return url.toLowerCase();
                    } else {
                        // 如果不是磁力链 就提取 连续字母数字32-40位
                        var match = /[\da-zA-Z]{32,40}/.exec(url);
                        if (match) {
                            return `magnet:?xt=urn:btih:${match[0]}`.toLowerCase();
                        }
                    }
                }
                return null;
            },
            // 提取时间
            extractDate: function (dateText) {
                if (dateText) {
                    var parser = [
                        {
                            // 2019-12-22
                            regx: /(\d{4})-(\d{1,2})-(\d{1,2})/,
                            format: ['YYYY-MM-DD']
                        },
                        {
                            // 2019-12-22 21:26
                            regx: /(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})/,
                            format: ['YYYY-MM-DD HH:mm']
                        },
                        {
                            // 2019-12-22 21:26:51
                            regx: /(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/,
                            format: ['YYYY-MM-DD HH:mm:ss']
                        },
                        {
                            // 12-22 2019
                            regx: /(\d{1,2})-(\d{1,2})(&nbsp;| )(\d{4})/,
                            format: 'MM-DD YYYY'
                        },
                        {
                            // 12-22 08:08
                            regx: /(\d{1,2})-(\d{1,2})(&nbsp;| )(\d{2}):(\d{2})/,
                            format: 'MM-DD HH:mm'
                        }
                    ];
                    for (let i = 0; i < parser.length; i++) {
                        var regx = parser[i].regx;
                        if (regx.test(dateText)) {
                            var exec = regx.exec(dateText);
                            var text = exec ? exec[0] : dateText;
                            return moment(text, parser[i].format).valueOf();
                        }
                    }
                    // 如果是时间间隔
                    if (/yesterday|昨天/.test(dateText)) {
                        return moment().subtract(1, 'day').valueOf();
                    } else {
                        var unit = [
                            {regx: 'yesterday|昨天', name: 'days'},
                            {regx: 'year|年', name: 'years'}, {regx: 'month|月', name: 'months'},
                            {regx: 'day|天', name: 'days'}, {regx: 'hour|小时', name: 'hour'},
                            {regx: 'minute|分钟', name: 'minutes'}, {regx: 'second|秒', name: 'seconds'}
                        ];
                        for (let i = 0; i < unit.length; i++) {
                            var dateTextMatches = new RegExp(`\\d+( {0,3})${unit[i].regx}`, 'gi').exec(dateText);
                            if (dateTextMatches) {
                                var number = $.xpathFormat.extractNumber(dateTextMatches[0]);
                                return moment().subtract(number, unit[i].name).valueOf();
                            }
                        }
                    }
                    return 0;
                }
             },
            // 提取文件大小（字节）
            extractFileSize: function (sizeText) {
                var sizeUnit = ['B|bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var sizeUnitSpare = ['B|bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
                var extSizeText = $.xpathFormat.extractSizeText(sizeText);
                if (extSizeText) {
                    var index = -1;
                    for (var i = sizeUnit.length - 1; i >= 0; i--) {
                        if (new RegExp(`${sizeUnit[i]}|${sizeUnitSpare[i]}`, 'i').test(sizeText)) {
                            index = i;
                            break
                        }
                    }
                    if (index >= 0) {
                        return parseInt($.xpathFormat.extractFloat(extSizeText) * Math.pow(1024, index));
                    }
                    return extSizeText;
                } else {
                    return sizeText;
                }
            },
            splitByFileSize: function (str) {
                var sizeUnit = ['B|bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
                var sizeUnitRegx = sizeUnit.join('|');
                var regx = new RegExp(`(\\d+(\\.\\d+)?) {1,3}(${sizeUnitRegx})$`, 'gi');
                var match = regx.exec(str);
                var filesize = match ? match[0] : str;
                var filename = str.replace(regx, '');
                var array = [filename, filesize];
                return array.filter(function (it) {
                    return it && $.trim(it);
                });
            }
        },
        // 弹出层封装处理
        modal: {
            bootstrap: {
                // 打开模态框
                open: function (modalId, url, data, option, width, height) {
                    var fatherBody = $(window.top.document.body);
                    var dialog = $('#' + modalId);
                    if (dialog.length == 0) {
                        dialog = $('<div class="modal fade" role="dialog" id="' + modalId + '"/>');
                        dialog.appendTo(fatherBody);
                    }
                    if (width) {
                        dialog.width(width);
                    }
                    if (height) {
                        dialog.width(height);
                    }
                    if (!option) {
                        option = {
                            keyboard: false, // 是否使用按键关闭窗口
                            backdrop: true   // 是否点击遮罩层关闭窗口
                        }
                    }
                    dialog.load(url, data, function() {
                        dialog.modal(option);
                    });
                    fatherBody.append("<div id='backdropId' class='modal-backdrop fade in'></div>");
                    // 隐藏模态框触发事件
                    dialog.on('hidden.bs.modal', function () {
                        fatherBody.find('#backdropId').remove();
                    });
                },
                // 关闭模态框
                close: function (modalId) {
                    var fatherBody = $(window.top.document.body);
                    //隐藏模态框触发事件
                    fatherBody.find('#' + modalId).on('hidden.bs.modal', function () {
                        fatherBody.find('#backdropId').remove();
                    });
                }
            },
            window: {
                // 打开新弹出窗口
                open: function (option) {
                    if (!option || option.url == undefined || option.url == null){
                        return null;
                    }

                    var url = option.url;
                    if (url.indexOf('?') != -1) {
                        url = url + '&r_=' + Math.random();
                    } else {
                        url = url + '?r_=' + Math.random();
                    }

                    var w, h, t, l;
                    if (!option.width) {
                        w = screen.width - 50;
                    } else {
                        w = parseInt(option.width);
                    }
                    if (!option.height) {
                        h = screen.height / 1.2;
                    } else {
                        if(option.height > screen.height / 1.2) {
                            h = screen.height / 1.2;
                        }else{
                            h = parseInt(option.height);
                        }
                    }
                    if (!option.top) {
                        // 获得窗口的垂直位置
                        t = (window.screen.availHeight - parseInt(h)) / 2 - 40;
                    } else{
                        t = parseInt(option.top);
                    }
                    if (!option.left) {
                        // 获得窗口的水平位置
                        l = (screen.width - parseInt(w)) / 2;
                    } else {
                        l = parseInt(option.left);
                    }

                    w = parseInt(w);
                    h = parseInt(h);
                    l = parseInt(l);
                    t = parseInt(t);

                    // 窗口句柄
                    var name;
                    if (!option.name) {
                        name = 'win_' + new Date().getTime();
                    } else {
                        name = option.name;
                    }

                    //是否可以改变窗口大小
                    var resizable = option.resizable || 'yes';
                    //是否有滚动条
                    var scrollbars= option.scrollbars || 'yes';
                    //是否有状态栏
                    var status = option.status || 'no';
                    //是否有菜单栏
                    var menubar = option.menubar || 'no';
                    //是否有工具栏
                    var toolbar = option.toolbar || 'no';
                    //是否有地址栏
                    var locations = option.locations || 'no';

                    return window.open(url, name, 'height=' + h + ',width=' + w + ',top=' + t + ',left=' + l +
                        ',toolbar=' + toolbar + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' +
                        resizable + ',location=' + locations + ', status=' + status + ',hotkeys=esc');
                },
                // 打开新窗口快捷方法
                open: function (url, w, h) {
                    var width = w || (screen.width - 50);
                    var height = h || screen.height / 1.2;

                    return $.modal.window.open({
                        url : url,
                        width : width,
                        height : height
                    });
                },
                // 获取当前窗口的父窗口
                parent: function () {
                    var p = '';
                    if (window.opener != undefined) {
                        p = window.opener;
                    }
                    else {
                        p = window.dialogArguments;
                    }
                    return p;
                }
            },
            lay: {
                _index: null,
                option: function (option, isHtml) {
                    var url = option.content;
                    var width = option.width, height = option.height;
                    // 移动端使用自适应大小
                    if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
                        // width = 'auto';
                        // height = 'auto';
                    }
                    if ($.common.isEmpty(option.title)) {
                        option.title = false;
                    }
                    if ($.common.isEmpty(url)) {
                        url = ctx + 'error/404';
                    }
                    if ($.common.isEmpty(width)) {
                        width = ($(window).width() - 50);
                    }
                    if ($.common.isEmpty(option.height)) {
                        height = ($(window).height() - 10);
                    }
                    if (width != 'auto') {
                        width += 'px';
                    }
                    if (height != 'auto') {
                        height += 'px';
                    }

                    // 点击遮罩关闭
                    if ($.common.isEmpty(option.shadeClose)) {
                        option.shadeClose = true;
                    }
                    // 最大最小化按钮
                    if ($.common.isEmpty(option.maxmin)) {
                        option.maxmin = true;
                    }
                    if ($.common.isEmpty(isHtml)) {
                        var union = (url.indexOf('?') > -0) ? '&' : '?';
                        url += union + 'iframeName=' + window.name;
                    }

                    $.extend(option, {
                        content: url,
                        area: [width, height],
                        maxmin: true,
                        anim: 1,
                        fix: false,
                        shade: 0.3
                    });
                    return option;
                },
                // 打开iframe弹窗
                openFrame: function (option, top) {
                    option = $.modal.lay.option(option);
                    $.extend(option, {
                        type: 2
                    });
                    if ($.common.isEmpty(top) || top == true) {
                        return window.top.layer.open(option);
                    } else {
                        return layer.open(option);
                    }
                },
                // 打开静态弹窗
                openHtml: function (option, top) {
                    option = $.modal.lay.option(option, true);
                    $.extend(option, {
                        type: 1
                    });
                    if ($.common.isEmpty(top) || top == true) {
                        return window.top.layer.open(option);
                    } else {
                        return layer.open(option);
                    }
                },
                // 打开最大化弹窗, type: 1:静态, 2:iframe
                openFull: function (option, type, top) {
                    option = $.modal.lay.option(option);
                    if ($.common.isEmpty(type)) {
                        type = 2;
                    }
                    $.extend(option, {
                        type: type,
                    });
                    var layer_index;
                    if ($.common.isEmpty(top) || top == true) {
                        layer_index = window.top.layer.open(option);
                        window.top.layer.full(layer_index);
                    } else {
                        layer_index = window.layer.open(option);
                        layer.full(layer_index);
                    }
                    return layer_index;
                },
                openPhoto: function (url) {
                    layer.photos({photos: {"data": [{"src": url}]}});
                },
                openVideo: function (url) {
                    var loadstr = '<video width="100%" height="100%"  controls="controls" autobuffer="autobuffer"  autoplay="autoplay" loop="loop">' +
                        '<source src=' + url + ' type="video/webm"></source></video>';

                    var width = ($(window).width() * 0.8) + 'px';
                    var height = ($(window).height() * 0.9) + 'px';

                    layer.open({
                        type: 1,
                        title: false,
                        area: [width, height],
                        shade: [0.8, 'rgb(14, 16, 22)'],
                        skin: 'demo-class',
                        content: loadstr
                    });
                },
                openAudio: function (url) {
                    var loadstr = '<audio src='+url+' controls="controls" style="width: 450px;height: 60px;" preload="auto"  autoplay="autoplay" loop="loop"></audio>';

                    window.layer.open({
                        type: 1,
                        title: false,
                        area: ['460px', '80px'],
                        shade: [0.8, 'rgb(14, 16, 22)'],
                        skin: 'demo-class',
                        content: loadstr
                    });
                },
                // 关闭当前弹窗
                close: function (index, top) {
                    if ($.common.isEmpty(top) || top == true) {
                        // 获取当前layer层的索引
                        var layer_index = index || window.top.layer.getFrameIndex(window.name);
                        window.top.layer.close(layer_index);
                    } else if (parent) {
                        // 获取当前layer层的索引
                        var layer_index = index || parent.layer.getFrameIndex(window.name);
                        parent.layer.close(layer_index); //再执行关闭
                    }
                },
                // 关闭所有弹窗
                closeAll: function () {
                    if (parent) {
                        parent.layer.closeAll();
                    }
                    top.layer.closeAll();
                },
                // 获取当前layer所以
                index: function (iframeName, top) {
                    if ($.common.isEmpty(iframeName)) {
                        iframeName = window.name;
                    }
                    var p;
                    if ($.common.isEmpty(top) || top == true) {
                        p = window.top;
                    } else {
                        p = parent;
                    }
                    return p.layer.getFrameIndex(iframeName);
                },
                // 打开等待遮罩层
                wait: function (message) {
                    return window.top.layer.msg(message, {
                        icon: 16,
                        shade: [0.5, '#f5f5f5'],
                        scrollbar: false,
                        offset: '0px',
                        time:100000});
                },
                // 消息提示
                msg: function(content, type) {
                    if (type != undefined) {
                        layer.msg(content, { icon: type, time: 2000, shift: 5 });
                    } else {
                        layer.msg(content);
                    }
                },
                // 错误消息
                msgError: function(content) {
                    $.modal.lay.msg(content, 2);
                },
                // 成功消息
                msgSuccess: function(content) {
                    $.modal.lay.msg(content, 1);
                },
                // 警告消息
                msgWarning: function(content) {
                    $.modal.lay.msg(content, 0);
                },
                // 消息提示并刷新父窗体
                msgReload: function(msg, type) {
                    $.modal.lay.msg(msg, {
                            icon: type,
                            time: 500,
                            shade: [0.1, '#8F8F8F']
                        },
                        function() {
                            $.modal.reload();
                        });
                },
                // 弹出提示
                alert: function(content, type, title) {
                    title = title || '提示';
                    window.top.layer.alert(content, {
                        icon: type,
                        title: title,
                        btn: ['确认'],
                        btnclass: ['btn btn-success']
                    });
                },
                // 错误提示
                alertError: function(content, title) {
                    $.modal.lay.alert(content, 'error', title);
                },
                // 成功提示
                alertSuccess: function(content, title) {
                    $.modal.lay.alert(content, 'success', title);
                },
                // 警告提示
                alertWarning: function(content, title) {
                    $.modal.lay.alert(content, 'warning', title);
                },
                // 确认窗体
                confirm: function (content, callBack, title) {
                    title = title || '提示';
                    window.top.layer.confirm(content, {
                        icon: 3,
                        title: title,
                        btn: ['确认', '取消'],
                        btnclass: ['btn btn-success', 'btn btn-danger']
                    }, function (index) {
                        window.top.layer.close(index);
                        callBack(true);
                    });
                },
                prompt: function(title, callBack) {
                    window.top.layer.prompt({title: title, formType: 0}, function(value, index){
                        window.top.layer.close(index);
                        callBack(value);
                    });
                },
                loading: function(icon) {
                    icon = icon || 0;
                    $.modal.lay._index = layer.load(icon, {shade: [0.8, '#393D49']});
                    return $.modal.lay._index;
                },
                closeLoading: function(index) {
                    index = index || $.modal.lay._index;
                    layer.close(index);
                }
            },
            toast: {
                option: function (option) {
                    $.extend(option, {
                        closeButton: option.closeBtn || false,
                        extendedTimeOut: 0,
                        timeOut: option.timeOut || 3000,
                        // toast-top-full-width 占满顶行, toast-top-right 右上
                        positionClass: option.positionClass || 'toast-top-right'
                    });
                    return option;
                },
                info: function (title, message) {
                    var title = title || false;
                    toastr.info(message, title, $.modal.toast.option({}));
                },
                warning: function (title, message) {
                    var title = title || false;
                    toastr.warning(message, title, $.modal.toast.option({}));
                },
                error: function (title, message) {
                    var title = title || false;
                    toastr.error(message, title, $.modal.toast.option({}));
                },
                success: function (title, message) {
                    var title = title || false;
                    toastr.success(message, title, $.modal.toast.option({}));
                },
                clear: function () {
                    toastr.clear();
                }
            },
            loading: function (msg) {
                var $overlay = public_vars.$pageLoading;
                if ($overlay.length) {
                    msg = msg || '';
                    $overlay.find('.loader').text(msg);
                    $overlay.removeClass('loaded');
                }
            },
            closeLoading: function () {
                var $overlay = public_vars.$pageLoading;
                if ($overlay.length) {
                    $overlay.toggle('loaded');
                    $overlay.addClass('loaded');
                }
            },
            // 禁用按钮
            disable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $('a[class*=layui-layer-btn]', doc).addClass('layer-disabled');
            },
            // 启用按钮
            enable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $('a[class*=layui-layer-btn]', doc).removeClass('layer-disabled');
            },
            // 重新加载
            reload: function () {
                parent.location.reload();
            }
        },
        // 表单封装处理
        form: {
            _bootstrapValidator: null,
            _validatorOptions: {
                container: 'tooltip',
                feedbackIcons: {
                    // valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                //live: 'enabled',
                excluded: [':disabled', ':hidden', ':not(:visible)', '.excluded'],
                submitButtons: '.form-submit'
            },
            // 表单赋值
            load: function(formId, jsonStr, readonly, filePrefix, srcPrefix) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var formField, fieldTagName, default_value;
                $.each(jsonStr, function (name, ival) {
                    var fieldName = $.common.nullToStr(filePrefix) + name;
                    formField = $('#' + form_id).find('[name="' + fieldName + '"]');
                    // 不存在元素，继续循环
                    if ($.type(formField[0]) === 'undefined') {
                        return true;
                    }
                    formField.each(function(index, field) {
                        $.form.setFieldValue(field, ival, formField, readonly, srcPrefix);
                    });
                });
            },
            // 表单字段赋值
            setFieldValue: function(field, ival, formField, readonly, srcPrefix) {
                var default_value = $(field).attr('default-value');
                if ($.common.isEmpty(ival)) {
                    ival = default_value;
                }
                if ($.common.isEmpty(ival)) {
                    return;
                }

                // 对象属性
                if ($(field).attr('childkey')) {
                    ival = ival[$(field).attr('childkey')];
                }

                // 只读字段
                if (readonly) {
                    $(field).attr('disabled', 'disabled');
                }

                var fieldTagName = field.tagName.toLowerCase();
                if (fieldTagName === 'input') {
                    if ($(field).attr('type') === 'radio' || formField.attr('type') === 'checkbox') {
                        var parent = $(field).parent().parent();

                        if ($(parent).hasClass('toggle-switch')) {
                            // switch开关赋值
                            if ('0' === ival) {
                                $(parent).bootstrapSwitch('setState', true);
                            } else if ('1' === ival) {
                                $(parent).bootstrapSwitch('setState', false);
                            }
                        } else {
                            var ival_ = '';
                            if (Object.prototype.toString.apply(ival) == '[object Array]') {
                                // 复选框，并且是数组
                                for (var i = 0; i < ival.length; i++) {
                                    ival_ += ',' + ival[i];
                                }
                                if (ival_.lengh > 0) {
                                    ival_ = ival_.substring(1);
                                }
                            } else {
                                ival_ = ival;
                            }
                            $(field).each(function () {
                                if ((',' + ival_ + ',').indexOf(',' + $(this).val() + ',') != -1) {
                                    $(this).iCheck('check');
                                } else {
                                    $(this).iCheck('uncheck');
                                }
                            });
                        }
                    } else if ($(field).attr('data-role') == 'tagsinput') {
                        $(field).tagsinput('add', ival);
                    } else {
                        $(field).val(ival);
                    }
                } else if (fieldTagName == 'select') {
                    var select2_flag = $(field).hasClass('select2');
                    var selectpicker_flag = $(field).hasClass('selectpicker');
                    if (select2_flag) {
                        var value = eval(ival);
                        $.each(value, function (index, data) {
                            var id = data.id;
                            $(field).append('<option value="' + id + '" selected>' + data.text + '</option>');
                        });
                    } else {
                        var value = ',';
                        if (Object.prototype.toString.apply(ival) == '[object Array]') {
                            for (var i = 0; i < ival.length; i++) {
                                value += ival[i] + ',';
                            }
                        } else {
                            value += ival + ',';
                        }

                        $.each(field.options, function (index_, data) {
                            if ((',' + data.value + ',').indexOf(value) >= 0) {
                                field.options[index_].selected = true;
                            }
                        });

                        if (selectpicker_flag) {
                            $(field).selectpicker('render');
                        }
                    }
                } else if (fieldTagName == 'textarea') {
                    $(field).val(ival);
                } else if (fieldTagName == 'img' || fieldTagName == 'image') {
                    if ($.common.isNotEmpty(ival)) {
                        if ($.common.startWith(ival, 'http')) {
                            $(field).attr('src', ival);
                        } else if (srcPrefix) {
                            $(field).attr('src', srcPrefix + ival);
                        }
                    }
                } else if (fieldTagName == 'p') {
                    $(field).text(ival);
                } else {
                    if (Object.prototype.toString.apply(ival) == '[object Array]') {
                        var actions = [];
                        for (var i = 0; i < ival.length; i++) {
                            actions.push("<span class='badge badge-success'>" + ival[i] + "</span>  ");
                        }
                        $(field).prepend(actions.join('  '));
                    } else {
                        $(field).val(ival);
                    }
                }
            },
            // 表单取值
            serialize: function(formId, switchArr, readonly) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var params = $('#' + form_id).serializeArray();
                if(switchArr) {
                    $.each(switchArr, function(index, value) {
                        if (params.indexOf(value + '=on') >= 0) {
                            params = params.replace(value + '=on', value + '=0');
                        } else {
                            if (params.indexOf('=') > 0) {
                                params += '&' + value + '=1';
                            } else {
                                params += '?' + value + '=1';
                            }
                        }
                    });
                }
                // 加载disabled字段
                if (readonly) {
                    $('input[disabled="disabled"]', '#' + form_id).each(function() {
                        if (params.indexOf('=') > 0) {
                            params += '&' + $(this).attr('name') + '=' + $(this).val();
                        } else {
                            params += '?' + $(this).attr('name') + '=' + $(this).val();
                        }
                    });
                }
                return params;
            },
            // 文件表单取值
            serializeFile: function(formId, switchArr, formData) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var params = $.form.serialize(form_id, switchArr);
                $.each(params.split('&'), function(index, value) {
                    if(params.indexOf('uploadFile') < 0) {
                        formData.append(value.split('=')[0], value.split('=')[1]);
                    }
                });
                return formData;
            },
            // 搜索表单取值
            serializeQuery: function(formId, switchArr) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var params = $('#' + form_id).serializeJSON();
                if(switchArr) {
                    $.each(switchArr, function(index, value) {
                        if('on' == params[value]) {
                            params[value] = '0';
                        } else {
                            params[value] = '1';
                        }
                    });
                }
                return params;
            },
            // 表单重置
            reset: function(formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $.form.resetSelect(formId);
                $.form.resetCheckbox(formId);
                $('#' + form_id)[0].reset();
                $('#' + form_id).find("input[type='hidden']").val(null);

                if ($.form._bootstrapValidator) {
                    $('#' + form_id).data("bootstrapValidator").resetForm();
                }
            },
            // select2重置
            resetSelect: function (formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var str = $("<span class='select2-selection__placeholder'> --请选择--</span>");
                $('.select2', '#' + form_id).each(function() {
                    var select_id = $(this).attr('id');
                    $(this).val('').trigger('change');
                    $('#select2-' + select_id + '-container').attr('title','');
                    $('#select2-' + select_id + '-container').prepend(str);
                    $('#select2-' + select_id + '-container').empty();
                });
            },
            // select2重置
            resetSelectById: function (selectId) {
                var str = $("<span class='select2-selection__placeholder'> --请选择--</span>");
                $('#selectId').val('').trigger('change');
                $('#select2-' + selectId + '-container').attr('title','');
                $('#select2-' + selectId + '-container').prepend(str);
                $('#select2-' + selectId + '-container').empty();
            },
            // checkbox重置
            resetCheckbox: function(formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $('input[type="checkbox"]', '#' + form_id).each(function() {
                    $(this).iCheck('uncheck');
                });
            },
            // checkbox重置
            resetRadio: function(formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $('input[type="radio"]', '#' + form_id).each(function() {
                    $(this).iCheck('uncheck');
                });
            },
            // 获取复选框选中项
            checked: function(name) {
                var checked = '';
                $('input:checkbox[name="' + name + '"]:checked').each(function(i) {
                    if (0 == i) {
                        checked = $(this).val();
                    } else {
                        checked += (',' + $(this).val());
                    }
                });
                return checked;
            },
            // 获取单选框选中项
            radioed: function(name) {
                var checked = '';
                $('input:radio[name="' + name + '"]:checked').each(function(i) {
                    if (0 == i) {
                        checked = $(this).val();
                    } else {
                        checked += (',' + $(this).val());
                    }
                });
                return checked;
            },
            // 获取选中下拉框项
            selected: function(selectId) {
                var selects = '';
                $('#' + selectId + ' option:selected').each(function (i) {
                    if (0 == i) {
                        selects = $(this).val();
                    } else {
                        selects += (',' + $(this).val());
                    }
                });
                return selects;
            },
            // 加载select2
            initSelect: function (selectId, url, selected) {
                // 加载选中项
                if (selected) {
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: url,
                        data: {
                            selected: selected
                        },
                        success: function (result) {
                            if (result.code == 200) {
                                $.each(result.param.data, function (id, data) {
                                    $('#' + selectId).append('<option value="' + data.id + '" selected>' + data.text + '</option>');
                                });
                            }
                        },error:function(data){ }
                    });
                }
                // 生成select2下拉菜单
                return $('#' + selectId).select2({
                    placeholder: '  --请选择--  ',
                    placeholderOption: 'first',
                    allowClear: true,
                    theme: 'classic',
                    language: 'zh-CN',
                    tags: true,
                    ajax: {
                        url: url,
                        delay: 100,
                        type : 'post',
                        data: function (params) {
                            return {
                                term: params.term,	        // 输入值
                                page: params.page || 1,	// 页码
                                length: '20'     		    // 每次获取数量
                            };
                        },
                        processResults: function (result, params) {
                            params.page = params.page || 1;
                            return {
                                results: result.param.data,
                                pagination: {
                                    more: (params.page * 20) < result.param.total
                                }
                            };
                        },
                        cache: true
                    },
                    // minimumInputLength: 2,
                    templateResult: function(data){
                        return data.text;
                    },
                    templateSelection: function(data){
                        return data.text;
                    }
                });
            },
            // 变更select2选中项
            changeSelectText: function (selectId, targetId) {
                $('#' + targetId).val($('#' + selectId).select2('data')[0].text);
            },
            // 变更select2选中项
            changeSelectValue: function (selectId, targetId) {
                $('#' + targetId).val($('#' + selectId).select2('val'));
            },
            // 变更select2选中项
            changeSelectValueText: function (selectId, target_id, target_text) {
                $('#' + target_id).val($('#' + selectId).select2('val'));
                $('#' + target_text).val($('#' + selectId).select2('data')[0].text);
            },
            // 加载日期组件
            renderDate: function (dateId, value, type, format, done) {
                var options = {};
                options.elem = '#' + dateId;
                options.theme = '#1E9FFF';
                options.calendar= true;
                if ($.common.isEmpty(type)) {
                    options.type = 'date';
                } else {
                    options.type = type;
                }
                if ($.common.isEmpty(format)) {
                    options.format = 'yyyy-MM-dd';
                } else {
                    options.format = format;
                }
                if (value) {
                    options.value = value;
                }
                if (done) {
                    options.done = done;
                }
                options.position = 'fixed';
                laydate.render(options);
            },
            renderDateRange: function (startId, endId) {
                var startDate = laydate.render({
                    elem: '#' + startId,
                    max: $('#' + endId).val(),
                    calendar: true,
                    theme: '#1E9FFF',
                    trigger: 'click',
                    done: function(value, date) {
                        // 结束时间大于开始时间
                        if (value !== '') {
                            endDate.config.min.year = date.year;
                            endDate.config.min.month = date.month - 1;
                            endDate.config.min.date = date.date;
                        } else {
                            endDate.config.min.year = '';
                            endDate.config.min.month = '';
                            endDate.config.min.date = '';
                        }
                    }
                });
                var endDate = laydate.render({
                    elem: '#' + endId,
                    min: $('#' + startId).val(),
                    theme: '#1E9FFF',
                    trigger: 'click',
                    done: function(value, date) {
                        // 开始时间小于结束时间
                        if (value !== '') {
                            startDate.config.max.year = date.year;
                            startDate.config.max.month = date.month - 1;
                            startDate.config.max.date = date.date;
                        } else {
                            startDate.config.max.year = '';
                            startDate.config.max.month = '';
                            startDate.config.max.date = '';
                        }
                    }
                });
            },
            initValidator: function (form_id, fields, extra) {
                var bootstrapValidator;
                var options = $.form._validatorOptions;
                fields = $.common.isEmpty(fields) ? {} : fields;
                if ($.common.isNotEmpty(extra)) {
                    $.extend(options, extra);
                }
                options.fields = fields;
                bootstrapValidator = $('#' + form_id).bootstrapValidator(options);
                //$('#' + form_id).data('bootstrapValidator').validate();
                $.form._bootstrapValidator = bootstrapValidator;
                return bootstrapValidator;
            },
            initValidatorRemote: function(formId, tableName, extra) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                if ($.form._bootstrapValidator) {
                    return $.form._bootstrapValidator;
                }

                var bootstrapValidator, datas;
                var options = $.form._validatorOptions;
                $.ajax({
                    async: false,
                    url: ctx + 'public/validator/option',
                    type: 'get',
                    data: {
                        tableName: tableName
                    },
                    success: function(result){
                        if (result.code == 200 && $.common.isNotEmpty(result.param)) {
                            $.each(result.param, function (index, row) {
                                if (row.validators.regexp) {
                                    var tmp = row.validators.regexp.regexp;
                                    this.validators.regexp.regexp = new RegExp(tmp);
                                    return true;
                                }
                            });

                            datas = result.param;
                        }
                    }
                });

                if($.common.isNotEmpty(datas) || $.common.isNotEmpty(extra)) {
                    datas = $.common.isEmpty(datas) ? {} : datas;
                    if ($.common.isNotEmpty(extra)) {
                        $.extend(datas, extra.fields);
                        $.extend(options, extra);
                    }
                    options.fields = datas;

                    bootstrapValidator = $('#' + form_id).bootstrapValidator(option);
                    $('#' + form_id).data('bootstrapValidator').validate();
                }
                $.form._bootstrapValidator = bootstrapValidator;
                return bootstrapValidator;
            },
            destroyValidator: function(formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                if ($.form._bootstrapValidator) {
                    $('#' + form_id).data('bootstrapValidator').destroy();
                    $('#' + form_id).data('bootstrapValidator', null);
                }
            },
            execValid: function (formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                if ($.form._bootstrapValidator) {
                    $('#' + form_id).data('bootstrapValidator').validate();
                }
            },
            isValid: function(formId) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                if ($.form._bootstrapValidator) {
                    var bootstrapValidator = $('#' + form_id).data('bootstrapValidator');
                    bootstrapValidator.validate();
                    return bootstrapValidator.isValid();
                }
                return true;
            },
            addValid: function (formId, field, options) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                if ($.form._bootstrapValidator) {
                    var bootstrapValidator = $('#' + form_id).data('bootstrapValidator');
                    bootstrapValidator.addField(field, options);
                    bootstrapValidator.validate();
                }
            }
        },
        // 表格封装处理
        table: {
            _table_id: 'bootstrap-table',
            _option: {},
            _selection: {},
            _params: {},
            _limit: 10,
            // 初始化表格
            init: function(tableId, options) {
                tableId = $.common.isEmpty(tableId) ? $.table._table_id : tableId;
                var defaults = {
                    height: undefined,
                    sidePagination: 'server',
                    sortName: '',
                    sortOrder: 'asc',
                    pageSize: 25,
                    pageList: [5, 10, 25, 50, 100],
                    toolbar: 'toolbar',
                    toolbarAlign: 'left',
                    striped: false,
                    escape: false,
                    showFooter: false,
                    pagination: true,
                    editable: false,
                    search: false,
                    showSearch: false,
                    showPageGo: true,
                    showRefresh: false,
                    showColumns: false,
                    showToggle: false,
                    showExport: false,
                    exportTypes: ['excel'],   // 导出文件格式'csv', 'txt', 'doc', 'excel'
                    clickToSelect: true,
                    singleSelect: false,
                    rememberSelected: false,
                    fixedColumns: false,
                    fixedNumber: 0,
                    fixedRightNumber: 0,
                    queryParams: $.table.queryParams,
                    rowStyle: {}
                };

                var options = $.extend(defaults, options);
                if (!options.code) {
                    options.code = options.columns[1].field;
                }
                $.table._option[tableId] = options;
                $.table._selection[tableId] = [];
                if (options.selected) {
                    $.map(options.selected.split(','), function (row) {
                        try {
                            $.table._selection[tableId].push(parseInt(row));
                        } catch (e) {
                            $.table._selection[tableId].push(row);
                        }
                    });
                }

                $.table._params[tableId] = options.queryParams;
                // 加载表格初始化事件
                $.table.initEvent(tableId, options);

                var table = $('#' + tableId).bootstrapTable({
                    url: options.url,                                   // 请求后台的URL（*）
                    contentType: "application/x-www-form-urlencoded",   // 编码类型
                    method: 'post',                                     // 请求方式（*）
                    cache: false,                                       // 是否使用缓存
                    height: options.height,                             // 表格的高度
                    striped: options.striped,                           // 是否显示行间隔色
                    sortable: true,                                     // 是否启用排序
                    sortStable: true,                                   // 设置为 true 将获得稳定的排序
                    editable: options.editable,                         // 表格编辑
                    sortName: options.sortName,                         // 排序列名称
                    sortOrder: options.sortOrder,                       // 排序方式  asc 或者 desc
                    pagination: options.pagination,                     // 是否显示分页（*）
                    pageNumber: 1,                                      // 初始化加载第一页，默认第一页
                    pageSize: options.pageSize,                         // 每页的记录行数（*）
                    pageList: options.pageList,                         // 可供选择的每页的行数（*）
                    escape: options.escape,                             // 转义HTML字符串
                    showFooter: options.showFooter,                     // 是否显示表尾
                    iconSize: 'outline',                                // 图标大小：undefined默认的按钮尺寸 xs超小按钮sm小按钮lg大按钮
                    toolbar: '#' + options.toolbar,                     // 指定工作栏
                    loadingFontSize: options.loadingFontSize,           // 自定义加载文本的字体大小
                    sidePagination: options.sidePagination,             // server启用服务端分页client客户端分页
                    search: options.search,                             // 是否显示搜索框功能
                    searchText: options.searchText,                     // 搜索框初始显示的内容，默认为空
                    showSearch: options.showSearch,                     // 是否显示检索信息
                    showPageGo: options.showPageGo,               		// 是否显示跳转页
                    showRefresh: options.showRefresh,                   // 是否显示刷新按钮
                    showColumns: options.showColumns,                   // 是否显示隐藏某列下拉框
                    showToggle: options.showToggle,                     // 是否显示详细视图和列表视图的切换按钮
                    showExport: options.showExport,                     // 是否支持导出文件
                    exportTypes: options.exportTypes,                   // 导出文件格式
                    exportFn: options.exportFn,                         // 导出文件方法
                    uniqueId: options.uniqueId,                         // 唯 一的标识符
                    clickToSelect: options.clickToSelect,				// 是否启用点击选中行
                    singleSelect: options.singleSelect,
                    cardView: options.cardView,                         // 是否启用显示卡片视图
                    detailView: options.detailView,                     // 是否启用显示细节视图
                    onCheck: options.onCheck,                           // 当选择此行时触发
                    onUncheck: options.onUncheck,                       // 当取消此行时触发
                    onCheckAll: options.onCheckAll,                     // 当全选行时触发
                    onUncheckAll: options.onUncheckAll,                 // 当取消全选行时触发
                    onClickRow: options.onClickRow,                     // 点击某行触发的事件
                    onDblClickRow: options.onDblClickRow,               // 双击某行触发的事件
                    onClickCell: options.onClickCell,                   // 单击某格触发的事件
                    onDblClickCell: options.onDblClickCell,             // 双击某格触发的事件
                    onExpandRow: options.onExpandRow,                   // 点击详细视图的事件
                    onReorderRow: options.onReorderRow,                 // 当拖拽结束后处理函数
                    maintainSelected: options.maintainSelected,         // 前端翻页时保留所选行
                    rememberSelected: options.rememberSelected,         // 启用翻页记住前面的选择
                    fixedColumns: options.fixedColumns,                 // 是否启用冻结列（左侧）
                    fixedNumber: options.fixedNumber,                   // 列冻结的个数（左侧）
                    fixedRightNumber: options.fixedRightNumber,         // 列冻结的个数（右侧）
                    queryParams: options.queryParams,                   // 传递参数（*）
                    rowStyle: options.rowStyle,                         // 通过自定义函数设置行样式
                    columns: options.columns,                           // 显示列信息（*）
                    data: options.data,                                 // 被加载的数据
                    exportOptions: options.exportOptions,               // 前端导出忽略列索引
                    detailFormatter: options.detailFormatter,           // 在行下面展示其他数据列表
                    onEditableSave: options.onEditableSave,             // 编辑表格调用
                    // 请求获取数据后处理回调函数
                    responseHandler: function (res) {
                        if (typeof options.responseHandler == "function") {
                            options.responseHandler(res);
                        }
                        if (res.code == 200) {
                            if ($.common.isNotEmpty(options.rememberSelected) && options.rememberSelected) {
                                var column = $.common.isEmpty(options.code) ? options.columns[1].field : options.code;
                                $.each(res.param.data, function (i, row) {
                                    row.rowState = $.inArray(row[column], $.table._selection[tableId]) !== -1;
                                });
                            }
                            return {rows: res.param.data, total: res.param.recordsTotal};
                        } else {
                            $.modal.toast.warning(res.msg, res.param);
                            return {rows: [], total: 0};
                        }
                    },
                    // 请求获取数据后处理回调函数
                    onLoadSuccess: function (data) {
                        // 浮动提示框特效
                        $("[data-toggle='tooltip']").tooltip();
                        // 下拉框展示
                        $('.bootstrap-table select.form-control.selectpicker').selectpicker('render');
                        // select2展示
                        $('.bootstrap-table select.form-control.select2').each(function () {
                         	$(this).select2();
                        });
                        if (typeof options.onLoadSuccess == "function") {
                            options.onLoadSuccess(data);
                        }
                    },
                    // 行渲染完成后执行
                    onPostBody: function (data) {
                        if (typeof options.onPostBody == "function") {
                            options.onPostBody(data);
                        }
                    }
                });
                return table;
            },
            // 初始化事件
            initEvent: function(table_id, option) {
                // 触发行点击事件 加载成功事件
                $('#' + table_id).on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table load-success.bs.table', function (e, row) {
                    // 工具栏按钮控制
                    var rows = $.common.isEmpty(option.code) ? $.table.selectFirstColumns(table_id, option) : $.table.selectColumns(option.code, table_id, option);
                    $('#' + option.toolbar + ' .btn-del').toggleClass('disabled', !rows.length);
                    $('#' + option.toolbar + ' .btn-edit').toggleClass('disabled', rows.length != 1);
                    $('#' + option.toolbar + ' .btn-detail').toggleClass('disabled', rows.length != 1);
                });
                // 绑定选中事件、取消事件、全部选中、全部取消
                $('#' + table_id).on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table', function (e, rows) {
                    // 复选框分页保留保存选中数组
                    var rowIds = $.table.affectedRowIds(rows, table_id);
                    if ($.common.isNotEmpty(option.rememberSelected) && option.rememberSelected) {
                        var func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
                        $.table._selection[table_id] = _[func]($.table._selection[table_id], rowIds);
                    }
                });
                // 图片预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('src');
                        if (src) {
                            $.modal.lay.openPhoto(src);
                        }
                    }
                }, '.img-circle, .img-square');
                // 视频预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('source');
                        if (src) {
                            $.modal.lay.openVideo(src);
                        }
                    }
                }, '.video-circle, .video-square');
                // 图片预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('source');
                        if (src) {
                            $.modal.lay.openAudio(src);
                        }
                    }
                }, '.audio-circle, .audio-square');
            },
            // 查询条件
            queryParams: function (params) {
                return {
                    // 传递参数查询参数
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search,
                    sort: params.sort,
                    order: params.order
                };
            },
            imageView: function(value, row, index) {
                if (value) {
                    if (!$.common.startWith(value, 'http')) {
                        value = ctx + 'public/file/preview/' + value;
                    }
                    return '<img class="img-circle" src="' + value + '" target="this"\/>';
                } else {
                    return '';
                }
            },
            videoView: function(value, row, index) {
                if (value) {
                    if (!$.common.startWith(value, 'http')) {
                        value = ctx + 'public/file/preview/' + value;
                    }
                    return '<img class="video-circle" src="' + ctx + 'image/file/file_video.png" source="' + value + '" target="this"\/>';
                } else {
                    return '';
                }
            },
            audioView: function(value, row, index) {
                if (value) {
                    if (!$.common.startWith(value, 'http')) {
                        value = ctx + 'public/file/preview/' + value;
                    }
                    return '<img class="audio-circle" src="' + ctx + 'image/file/file_music.png" source="' + value + '" target="this"\/>';
                } else {
                    return '';
                }
            },
            // 搜索
            search: function (table_id, form_id, switchArr) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(form_id)) {
                    form_id = $('form').attr('id');
                }
                var params = $('#' + table_id).bootstrapTable('getOptions');
                params.queryParams = function (params) {
                    var search = {};
                    var params_ = $.table._params[table_id].call(this, params);
                    $.extend(search, params_);
                    $.each($.form.serializeQuery(form_id, switchArr), function (name, value) {
                        if (value) {
                            search[name] = value;
                        }
                    });
                    return search;
                };
                $('#' + table_id).bootstrapTable('refreshOptions', params);
            },
            searchByParam: function (table_id, params) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                var options = $('#' + table_id).bootstrapTable('getOptions');
                options.queryParams = function (param) {
                    var search = {};
                    var params_ = $.table._params[table_id].call(this, param);
                    $.extend(search, params_);
                    $.extend(search, params);
                    search['offset'] = 1;
                    return search;
                };
                $('#' + table_id).bootstrapTable('refreshOptions', options);
            },
            // 查询表格首列值
            selectFirstColumns: function (table_id, option) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(option)) {
                    option = $.table._option[table_id];
                }

                var rows = $.map($('#' + table_id).bootstrapTable('getSelections'), function (row) {
                    return row[$.table._option[table_id].code];
                });
                if ($.common.isNotEmpty(option.rememberSelected) && option.rememberSelected) {
                    rows = rows.concat(selectionIds);
                }
                return $.common.uniqueFn(rows);
            },
            // 查询表格指定列值
            selectColumns: function (column, table_id, option) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(option) && table_id) {
                    option = $.table._option[table_id];
                }
                if ($.common.isEmpty(column)) {
                    column = $.table._option[table_id].code;
                }

                var rows = $.map($('#' + table_id).bootstrapTable('getOptions'), function (row) {
                    if (Array.isArray(row)) {
                        return row[column];
                    }
                    return false;
                });
                if ($.common.isNotEmpty(option.rememberSelected) && option.rememberSelected) {
                    rows = rows.concat($.table._selection[table_id]);
                }
                return rows;
            },
            totalRowCount: function (table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                return $('#' + table_id).bootstrapTable("getOptions").totalRows;
            },
            // 获取当前页选中或者取消的行ID
            affectedRowIds: function (rows, table_id, option) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(option) && table_id) {
                    option = $.table._option[table_id];
                }

                var column = $.common.isEmpty(option.code) ? option.columns[1].field : option.code;
                var rowIds;
                if ($.isArray(rows)) {
                    rowIds = $.map(rows, function (row) {
                        return row[column];
                    });
                } else {
                    rowIds = [rows[column]];
                }
                return rowIds;
            },
            // 获取当前页选中或者取消的行ID
            affectedRowColumns: function(rows, column) {
                var rowColumns;
                if ($.isArray(rows)) {
                    rowColumns = $.map(rows, function(row) {
                        return row[column];
                    });
                } else {
                    rowColumns = [rows[column]];
                }
                return rowColumns;
            },
            // 刷新表格
            refresh: function (table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                $('#' + table_id).bootstrapTable('refresh', {
                    silent: true
                });
            },
            // 序列号生成
            serialNumber: function(index, tableId) {
                var currentId = $.common.isEmpty(tableId) ? $.table._table_id : tableId;
                var tableParams = $("#" + currentId).bootstrapTable('getOptions');
                var pageSize = tableParams.pageSize;
                var pageNumber = tableParams.pageNumber;
                return pageSize * (pageNumber - 1) + index + 1;
            },
            // 获取当前排序结果
            sortResult: function (column, table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(column) && table_id) {
                    var option = $.table._option[table_id];
                    column = $.common.isEmpty(option.code) ? option.columns[1].field : option.code;
                }

                //获取首页数据
                var data = $('#' + table_id).bootstrapTable('getData', true);
                var jsonStr = '[';

                if ($.isArray(data)) {
                    $.map(data, function (row) {
                        jsonStr += '{id:"' + column + '",value:"' + row[column] + '"},';
                        return row;
                    });
                }

                if (jsonStr != '[') {
                    jsonStr = jsonStr.substring(0, jsonStr.length-1);
                    jsonStr += ']';
                    return jsonStr;
                } else {
                    return null;
                }
            },
            // 导出数据
            exportExcel: function(url, formId, switchArr) {
                var form_id = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $.modal.loading('正在导出数据，请稍后...');
                $.post(url, $.form.serializeQuery(formId, switchArr), function(result) {
                    if (result.code == 200) {
                        window.location.href = ctx + 'public/file/download?path=' + encodeURI(result.param) + '&delete=' + true;
                    } else {
                        $.modal.toast.error(result.msg, result.param);
                    }
                    $.modal.closeLoading();
                });
            },
            // 导出模板
            exportTemplate: function(url) {
                window.location.href = url;
            },
            // 导入数据
            importExcel: function(formId, url) {
                var form_id = $.common.isEmpty(formId) ? 'importForm' : formId;
                $.modal.lay.openHtml({
                    area: ['400px', '230px'],
                    fix: false,
                    maxmin: true,
                    shade: 0.3,
                    title: '导入数据',
                    content: $('#' + form_id),
                    btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
                    // 弹层外区域关闭
                    shadeClose: false,
                    btn1: function(index, layero){
                        var file = layero.find('#file').val();
                        if (file == '') {
                            $.modal.toast.warning('请选择文件');
                            return false;
                        }
                        $.modal.disable();
                        var formData = new FormData();
                        formData.append('file', $('#file')[0].files[0]);
                        formData.append('updateSupport', $('input[name="updateSupport"]').is(':checked'));
                        $.modal.loading('文件上传中，请稍后...');
                        $.ajax({
                            url: url,
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            type: 'post',
                            success: function (result) {
                                if (result.code == 200) {
                                    $.modal.toast.success(result.msg);
                                    $.modal.lay.close(index);
                                } else {
                                    $.modal.toast.error(result.msg, result.param);
                                    $.modal.enable();
                                }

                                $.modal.closeLoading();
                            },
                            error: function (err) {
                                $.modal.closeLoading();
                            }
                        });
                    }
                });
            },
            // 显示表格指定列
            showColumn: function (column, table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(option) && table_id) {
                    option = $.table._option[table_id];
                }
                $('#' + table_id).bootstrapTable('showColumn', column);
            },
            // 隐藏表格指定列
            hideColumn: function (column, table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                $('#' + table_id).bootstrapTable('hideColumn', column);
            },
            // 表格销毁
            destroy: function (tableId) {
                var currentId = $.common.isEmpty(tableId) ? $.table._table_id : tableId;
                $('#' + currentId).bootstrapTable('destroy');
            },
            // 选中的主键
            getSelectCode: function (column, table_id, option) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                if ($.common.isEmpty(option) && table_id) {
                    option = $.table._option[table_id];
                }
                if ($.common.isNotEmpty(option.rememberSelected) && option.rememberSelected) {
                    return $.table._selection[table_id];
                }
                if ($.common.isEmpty(column)) {
                    column = $.common.isEmpty(option.code) ? option.columns[1].field : option.code;
                }

                var rows = $('#' + table_id).bootstrapTable('getSelections');
                var results = [];
                if ($.common.isNotEmpty(rows)) {
                    $.map(rows, function (row) {
                        results.push(row[column])
                    });
                }
                return results;
            },
            updateColumn: function(index, field, value, table_id) {
                if ($.common.isEmpty(table_id)) {
                    table_id = $.table._table_id;
                }
                $('#' + table_id).bootstrapTable('updateCell', {
                    index: index,
                    field: field,
                    value: value
                });
            }
        },
        // 表格树封装处理
        treeTable: {
            _table_id: 'bootstrap-tree-table',
            _option: {},
            _params: {},
            // 初始化表格
            init: function(tableId, options) {
                tableId = $.common.isEmpty(tableId) ? $.treeTable._table_id : tableId;
                var defaults = {
                    height: 0,
                    rootIdValue: null,
                    ajaxParams: {},
                    toolbar: 'toolbar',
                    striped: false,
                    expandColumn: 1,
                    showRefresh: true,
                    showColumns: true,
                    expandAll: true,
                    expandFirst: true
                };
                var options = $.extend(defaults, options);
                $.treeTable._option[tableId] = options;

                // 加载表格初始化事件
                $.treeTable.initEvent(tableId);

                var treeTable = $('#' +  tableId).bootstrapTreeTable({
                    code: options.code,                                 // 用于设置父子关系
                    parentCode: options.parentCode,                     // 用于设置父子关系
                    type: 'post',                                       // 请求方式（*）
                    url: options.url,                                   // 请求后台的URL（*）
                    ajaxParams: options.ajaxParams,                     // 请求数据的ajax的data属性
                    rootIdValue: options.rootIdValue,                   // 设置指定根节点id值
                    expandColumn: options.expandColumn,                 // 在哪一列上面显示展开按钮
                    striped: options.striped,                           // 是否显示行间隔色
                    bordered: true,                                     // 是否显示边框
                    toolbar: '#' + options.toolbar,                     // 指定工作栏
                    iconSize: 'sm',                                     // 图标大小：undefined默认的按钮尺寸 xs超小按钮sm小按钮lg大按钮
                    height: options.height,
                    showRefresh: $.common.visible(options.showRefresh), // 是否显示刷新按钮
                    showColumns: $.common.visible(options.showColumns), // 是否显示隐藏某列下拉框
                    expandAll: $.common.visible(options.expandAll),     // 是否全部展开
                    expandFirst: $.common.visible(options.expandFirst), // 是否默认第一级展开--expandAll为false时生效
                    columns: options.columns,
                    rowClick: $.treeTable.rowClick
                });
                return treeTable;
            },
            // 初始化事件
            initEvent: function(table_id) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                // 图片预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('src');
                        if (src) {
                            $.modal.lay.openPhoto(src);
                        }
                    }
                }, '.img-circle, .img-square');
                // 视频预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('source');
                        if (src) {
                            $.modal.lay.openVideo(src);
                        }
                    }
                }, '.img-circle, .img-square');
                // 音频预览事件
                $('#' + table_id).on({
                    click: function() {
                        var src = $(this).attr('source');
                        if (src) {
                            $.modal.lay.openVideo(src);
                        }
                    }
                }, '.img-circle, .img-square');
            },
            rowClick: function(table_id) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                // 工具栏按钮控制
                var column = $.common.isEmpty($.treeTable._option[table_id].code) ? $.treeTable._option[table_id].columns[1].field : $.treeTable._option[table_id].code;
                var rows = $.treeTable.selectColumns(column, table_id);
                $('#' + $.treeTable._option[table_id].toolbar + ' .btn-del').toggleClass('disabled', !rows.length);
                $('#' + $.treeTable._option[table_id].toolbar + ' .btn-edit').toggleClass('disabled', rows.length != 1);
            },
            // 条件查询
            search: function(table_id, form_id, switchArr) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                form_id = $.common.isEmpty(form_id) ? $('form').attr('id') : form_id;
                var params = {};
                $.each($.form.serializeQuery(form_id, switchArr), function(name, value) {
                    if ($.common.isNotEmpty(value)) {
                        params[name] = value;
                    }
                });
                $('#' +  table_id).bootstrapTreeTable('refresh', params);
            },
            // 查询表格树指定列值
            selectColumns: function(column, table_id) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                var rows = $.map($('#' + table_id).bootstrapTreeTable('getSelections'), function (row) {
                    return row[column];
                });
                return $.common.uniqueFn(rows);
            },
            toggleExpand: function(table_id) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                var expandAll = $.common.isEmpty($.treeTable._option[table_id].expandAll) ? true : $.treeTable._option[table_id].expandAll;
                $.treeTable._option[table_id].expandAll = expandAll;
                if (!expandAll) {
                    $('#' + table_id).bootstrapTreeTable('expandAll');
                } else {
                    $('#' + table_id).bootstrapTreeTable('collapseAll');
                }
            },
            // 刷新
            refresh: function(table_id) {
                table_id = $.common.isEmpty(table_id) ? $.treeTable._table_id : table_id;
                $('#' +  table_id).bootstrapTreeTable('refresh');
            }
        },
        // 树插件封装处理
        tree: {
            _tree_id: 'tree',
            _tree: {},
            _option: {},
            _lastValue: {},
            _checkType: {},
            // 初始化树结构
            init: function(id, options, root, selected) {
                $.tree._tree_id = id || 'tree';
                var defaults = {
                    id: id,                    // 属性ID
                    expandLevel: 0,            // 展开等级节点
                    view: {
                        fontCss: {'color':'black','font-weight':'bold'},//字体样式函数
                        selectedMulti: false,                           // 设置是否允许同时选中多个节点
                        nameIsHTML: true                                // 设置 name 属性是否支持 HTML 脚本
                    },
                    check: {
                        enable: false,             // 置 zTree 的节点上是否显示 checkbox / radio
                        nocheckInherit: false      // 设置子节点是否自动继承
                    },
                    data: {
                        key: {
                            title: 'title'         // 节点数据保存节点提示信息的属性名称
                        },
                        simpleData: {
                            enable: true,
                            idKey: 'id',
                            pIdKey: 'pId',
                            rootPId: '0'
                        }
                    }
                };
                var options = $.extend(defaults, options);

                $.tree._checkType[id] = options.check.enable;
                $.tree._option[id] = options;
                // 树结构初始化加载
                var setting = {
                    callback: {
                        onClick: options.onClick,                      // 用于捕获节点被点击的事件回调函数
                        onCheck: options.onCheck,                      // 用于捕获 checkbox / radio 被勾选 或 取消勾选的事件回调函数
                        onDblClick: options.onDblClick,                // 用于捕获鼠标双击之后的事件回调函数
                        onRightClick: options.onRightClick             // 用户捕获鼠标右击事件回调函数
                    },
                    expandLevel: options.expandLevel,
                    check: options.check,
                    view: options.view,
                    data: options.data
                };

                var tree;
                if (options.async) {
                    //点击加载下级数据
                    setting.async = options.async;
                    options.url = options.async.url;
                    tree = $.fn.zTree.init($('#' + id), setting, root);
                    $.tree._tree[id] = tree;
                } else {
                    // 一次性加载全部数据
                    options.data = $.common.isEmpty(options.data) ? {} : options.data;
                    $.post(options.url, options.data, function(data) {
                        tree = $.fn.zTree.init($('#' + id), setting, data);
                        $.tree._tree[id] = tree;
                        var nodes = tree.getNodesByParam('level', options.expandLevel - 1);
                        for (var i = 0; i < nodes.length; i++) {
                            tree.expandNode(nodes[i], true, false, false);
                        }
                        if (selected) {
                            $.map(selected.split(','), function (select) {
                                var node = tree.getNodesByParam('id', select, null)[0];
                                $.tree.selectByIdName(node);
                            });
                        }
                    });
                }
                return tree;
            },
            // 根据Id和Name选中指定节点
            selectByIdName: function(node, treeId) {
                treeId = treeId || $.tree._tree_id;
                if ($.common.isNotEmpty(treeId) && node && treeId == node.id) {
                    $.tree._tree[treeId].selectNode(node, true);
                    if ($.tree._checkType[treeId]) {
                        $.tree._tree[treeId].checkNode(node, true, true);
                    }
                }
            },
            // 搜索节点
            searchNode: function(keyword, treeId) {
                treeId = treeId || $.tree._tree_id;
                // 取得输入的关键字的值
                var value = $.common.trim($('#' + keyword).val());
                if ($.tree._lastValue[treeId] && $.tree._lastValue[treeId] == value) {
                    return;
                }
                // 保存最后一次搜索名称
                $.tree._lastValue[treeId] = value;
                var nodes = $.tree._tree[treeId].getNodes();
                // 如果要查空字串，就退出不查了。
                if (value == '') {
                    $.tree.showAll(nodes, treeId);
                    return;
                }
                $.tree.hideAll(nodes, treeId);
                // 根据搜索值模糊匹配
                $.tree.updateNodes($.tree._tree[treeId].getNodesByParamFuzzy('name', value), treeId);
            },
            openNode: function (name, value, treeId) {
                treeId = treeId || $.tree._tree_id;
                var node = $.tree._tree[treeId].getNodeByParam(name, value, null);
                if (node) {
                    if (!node.open) {
                        $.tree._tree[treeId].reAsyncChildNodes(node, 'refresh');
                    }
                } else {
                    setTimeout(function () {
                        $.tree.openNode(name, value, treeId);
                    }, 10)
                }
            },
            // 显示所有节点
            showAll: function(nodes, treeId) {
                treeId = treeId || $.tree._tree_id;
                nodes = $.tree._tree[treeId].transformToArray(nodes, treeId);
                for (var i = nodes.length - 1; i >= 0; i--) {
                    if (nodes[i].getParentNode() != null) {
                        $.tree._tree[treeId].expandNode(nodes[i], true, false, false, false);
                    } else {
                        $.tree._tree[treeId].expandNode(nodes[i], true, true, false, false);
                    }
                    $.tree._tree[treeId].showNode(nodes[i]);
                    $.tree.showAll(nodes[i].children, treeId);
                }
            },
            // 隐藏所有节点
            hideAll: function (nodes, treeId) {
                treeId = treeId || $.tree._default_id;
                var nodes = $.tree._tree[treeId].transformToArray(nodes);
                for (var i = nodes.length - 1; i >= 0; i--) {
                    $.tree._tree[treeId].hideNode(nodes[i]);
                }
            },
            // 显示所有父节点
            showParent: function (treeNode, treeId) {
                treeId = treeId || $.tree._tree_id;
                var parentNode;
                while ((parentNode = treeNode.getParentNode()) != null) {
                    $.tree._tree[treeId].showNode(parentNode);
                    $.tree._tree[treeId].expandNode(parentNode, true, false, false);
                    treeNode = parentNode;
                }
            },
            // 显示所有孩子节点
            showChildren: function (treeNode, treeId) {
                treeId = treeId || $.tree._tree_id;
                if (treeNode.isParent) {
                    for (var idx in treeNode.children) {
                        var node = treeNode.children[idx];
                        $.tree._tree[treeId].showNode(node);
                        $.tree.showChildren(node, treeId);
                    }
                }
            },
            // 更新页面treeId和treeName
            updateIdName: function(event, treeElement, treeNode, type) {
                var treeId, treeName;
                type = $.common.isEmpty(type) ? {} : type;
                if (treeNode.checked) {
                    treeId = treeNode.id;
                    treeName = treeNode.name;
                }
                if (type.multi) {
                    var treeIds = [];
                    treeIds.push($('#treeId').val().split(','));
                    var treeNames = [];
                    treeNames.push($('#treeName').val().split(','));

                    if (treeId) {
                        // 添加元素
                        treeIds.push(treeId);
                        treeNames.push(treeName);
                    } else {
                        // 删除元素
                        var index = treeIds.indexOf(treeNode.id);
                        if (index > -1) {
                            treeIds.splice(index, 1);
                            treeNames.splice(index, 1);
                        }
                    }
                    $('#treeId').val(treeIds.join(','));
                    $('#treeName').val(treeNames.join(','));
                } else if(type.single) {
                    $('#treeId').val(treeId);
                    $('#treeName').val(treeName);
                } else {
                    $('#treeId').val(treeNode.id);
                    $('#treeName').val(treeNode.name);
                }
            },
            // 更新节点状态
            updateNodes: function (nodeList, treeId) {
                treeId = treeId || $.tree._tree_id;
                $.tree._tree[treeId].showNodes(nodeList);
                for (var i = 0, l = nodeList.length; i < l; i++) {
                    var treeNode = nodeList[i];
                    $.tree.showChildren(treeNode, treeId);
                    $.tree.showParent(treeNode, treeId);
                }
            },
            // 获取当前被勾选集合
            getCheckedNodes: function (column, treeId) {
                treeId = treeId || $.tree._tree_id;
                var _column = $.common.isEmpty(column) ? 'id' : column;
                var nodes = $.tree._tree[treeId].getCheckedNodes(true);
                return $.map(nodes, function (row) {
                    return row[_column];
                }).join();
            },
            // 不允许根父节点选择
            notAllowParents: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                var nodes = $.tree._tree[treeId].getSelectedNodes();
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].level == 0) {
                        $.modal.toast.error('不能选择根节点（' + nodes[i].name + '）');
                        return false;
                    }
                    if (nodes[i].isParent) {
                        $.modal.toast.error('不能选择父节点（' + nodes[i].name + '）');
                        return false;
                    }
                }
                return true;
            },
            // 不允许最后层级节点选择
            notAllowChild: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                var nodes = $.tree._tree[treeId].getSelectedNodes();
                for (var i = 0; i < nodes.length; i++) {
                    if (!nodes[i].isParent) {
                        $.modal.toast.error('不能选择最后层级节点（' + nodes[i].name + '）');
                        return false;
                    }
                }
                return true;
            },
            // 隐藏/显示搜索栏
            toggleSearch: function() {
                $('#search').slideToggle(200);
                $('#btnShow').toggle();
                $('#btnHide').toggle();
                $('#keyword').focus();
            },
            // 折叠
            collapse: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                $.tree._tree[treeId].expandAll(false);
            },
            // 展开
            expand: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                $.tree._tree[treeId].expandAll(true);
            },
            checkAllNodes: function (checked, treeId) {
                treeId = treeId || $.tree._tree_id;
                $.tree._tree[treeId].checkAllNodes(checked);
            },
            // 展示右键菜单
            showRMenu: function (type, x, y, treeId) {
                treeId = treeId || $.tree._tree_id;
                $('.' + treeId + '.tree-rMenu ul').show();
                //设置右键菜单的位置、可见
                $('.' + treeId + '.tree-rMenu').css({
                    'top': y + 'px',
                    'left': x + 'px',
                    'visibility': 'visible'
                });
                $('body').bind('mousedown', function(e) {
                    if (0 == e.button) {
                        $.tree.onBodyMouseDown(treeId)
                    }
                });
            },
            // 隐藏右键菜单
            hideRMenu: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                //设置右键菜单不可见
                if ($('.' + treeId + '.tree-rMenu'))
                    $('.' + treeId + '.tree-rMenu').css({'visibility': 'hidden'});
                $('body').unbind('mousedown', $.tree.onBodyMouseDown(treeId));
            },
            // 鼠标按下事件
            onBodyMouseDown: function (treeId) {
                treeId = treeId || $.tree._tree_id;
                if (!(event.target.css == ('.' + treeId + '.tree-rMenu') || $(event.target).parents('.' + treeId + '.tree-rMenu').length > 0)) {
                    $('.' + treeId + '.tree-rMenu').css({'visibility': 'hidden'});
                }
            }
        },
        // 操作封装处理
        operate: {
            // 提交数据
            submit: function(option, close, frame, callback) {
                close = $.common.isEmpty(close) ? false : close;

                if (!option.beforeSend) {
                    $.extend(option, {
                        beforeSend: function() {
                            $.modal.loading('处理中，请稍后...');
                        }
                    });
                }
                if (!option.success) {
                    $.extend(option, {
                        success: function(result) {
                            $.operate.ajaxSuccess(result, close, frame, callback);
                        }
                    });
                }
                if (!option.error) {
                    $.extend(option, {
                        error: function(result) {
                            window.location.href = ctx + 'error/500?errInfo=' + result.message;
                        }
                    });
                }

                if (!option.header) {
                    option.header = {};
                }

                $.extend(option.header, {
                    'Authorization': 'Bearer ' + $.common.cookie.get('PIECE_SESSIONID'),
                    'TenantHeader': 'Basic ' + $.common.cookie.get('PIECE_TENANT')
                });

                $.extend(option, {
                    complete: function() {
                        $.modal.closeLoading();
                    }
                });

                $.ajax(option);
            },
            // post请求
            post: function(option, close, frame, callback) {
                close = $.common.isEmpty(close) ? false : close;
                option.type = 'post';
                option.dataType = 'json';
                $.operate.submit(option, close, frame, callback);
            },
            // get请求
            get: function(option, close, frame, callback) {
                close = $.common.isEmpty(close) ? false : close;
                option.type = 'get';
                option.dataType = 'json';
                option.data = option.data || {};
                $.operate.submit(option, close, frame, callback);
            },
            // 保存结果
            ajaxSuccess: function (result, close, frame, callback) {
                if (result.code == 200) {
                    var content = result.msg || '';
                    $.modal.toast.success(content);
                    // 回调函数
                    var fn;
                    if (frame && callback) {
                        var frameIndex = $.common.iframe.get(frame);
                        if(window.execScript) {
                            // 给IE的特殊待遇
                            try {
                                fn = frameIndex.window.execScript(callback);
                            } catch (e) {
                                fn = frameIndex.window.frames['iframe_active'].window.execScript(callback);
                            }
                        } else {
                            // 给其他大部分浏览器用的
                            try {
                                fn = frameIndex.window.eval(callback);
                            } catch (e) {
                                fn = frameIndex.window.frames['iframe_active'].window.eval(callback);
                            }
                        }

                        if (fn) fn.call(this, result.param);
                    } else if (callback) {
                        if(window.execScript) {
                            // 给IE的特殊待遇
                            fn = window.execScript(callback);
                        } else {
                            // 给其他大部分浏览器用的
                            fn = window.eval(callback);
                        }

                        if (fn) fn.call(this, result.param);
                    }
                    // 关闭当前窗口
                    if (close) {
                        setTimeout(function () {
                            $.modal.lay.close();
                        }, 1500);
                    }
                } else {
                    $.modal.toast.error(result.msg, result.param);
                }
            },
            // 新增、修改信息
            edit: function(option) {
                option.title = option.title || '';
                var url = option.content;
                if (option._callback) {
                    var _index = option._index || window.name;
                    if (url.indexOf('?') > -1) {
                        url += '&layer_index=' + _index + '&layer_callback=' + option._callback;
                    } else {
                        url += '?layer_index=' + _index + '&layer_callback=' + option._callback;
                    }
                    option.content = url;
                }
                if ($.common.isEmpty(option.shadeClose)) {
                    option.shadeClose = true;
                }

                $.modal.lay.openFrame(option);
            },
            // 新增、修改信息
            editFull: function(option) {
                option.title = option.title || '';
                var url = option.content;
                if (option._callback) {
                    var _index = option._index || window.name;
                    if (url.indexOf('?') > -1) {
                        url += '&layer_index=' + _index + '&layer_callback=' + option._callback;
                    } else {
                        url += '?layer_index=' + _index + '&layer_callback=' + option._callback;
                    }
                    option.content = url;
                }
                $.modal.lay.openFull(option, 2);
            },
            // 新增、修改信息,从table、treetable中获取选中值
            editSelect: function(id, option, full) {
                var code;
                var type = option.type || 'table';
                if ('treeTable' == type) {
                    id = id || $.treeTable._table_id;
                    var rows = $('#' + id).bootstrapTreeTable('getSelections');
                    if ($.common.isEmpty(rows) || rows.length != 1) {
                        $.modal.toast.warning('请选择一条记录');
                        return;
                    }
                    code = rows[0][$.treeTable._option[id].code];
                } else if ('table' == type) {
                    id = id || $.table._table_id;
                    var rows = $('#' + id).bootstrapTable('getSelections');
                    if ($.common.isEmpty(rows) || rows.length != 1) {
                        $.modal.toast.warning('请选择一条记录');
                        return;
                    }
                    code = rows[0][$.table._option[id].code];
                }
                if (code) {
                    option.content = option.content.replace('{id}', code);
                    if (full) {
                        return $.operate.editFull(option);
                    } else {
                        return $.operate.edit(option);
                    }
                }
            },
            // 删除信息
            remove: function(url, id, msg, callback) {
                msg = msg || '确定删除该条数据吗？';
                var data = { 'ids': id };
                $.modal.lay.confirm(msg, function() {
                    $.ajax({
                        url: url,
                        // headers: {
                        //     'Authorization': authorization
                        // },
                        data: data,
                        type: 'post',
                        dataType: 'json',
                        success: function(result) {
                            if (result.code == 200) {
                                $.modal.toast.success(result.msg);
                                if (callback) {
                                    var fn;
                                    if(window.execScript) {
                                        // 给IE的特殊待遇
                                        fn = window.execScript(callback);
                                    } else {
                                        // 给其他大部分浏览器用的
                                        fn = window.eval(callback);
                                    }

                                    if (fn) fn.call(this);
                                }
                            } else {
                                $.modal.toast.error(result.msg, result.param);
                            }
                        }
                    });
                });
            },
            // 删除信息
            removeSelect: function(id, url, msg, type, callback) {
                var code = '', rows, key;
                var type = type || 'table';
                if ('treeTable' == type) {
                    id = id || $.treeTable._table_id;
                    rows = $('#' + id).bootstrapTreeTable('getSelections');
                    if ($.common.isEmpty(rows)) {
                        $.modal.toast.warning('请至少选择一条记录');
                        return;
                    }
                    key = $.treeTable._option[id].code;
                    $.each(rows, function(index, row){
                        code += row[key] + ',';
                    });
                } else if ('table' == type) {
                    id = id || $.table._table_id;
                    if ($.table._option[id].rememberSelected) {
                        rows = $.table._selection[id];
                    } else {
                        rows = $('#' +id).bootstrapTable('getSelections');
                    }
                    if ($.common.isEmpty(rows)) {
                        $.modal.toast.warning('请至少选择一条记录');
                        return;
                    }
                    key = $.table._option[id].code;
                    $.each(rows, function(index, row){
                        if ($.table._option[id].rememberSelected) {
                            code += row + ',';
                        } else {
                            code += row[key] + ',';
                        }
                    });
                }

                code = code.substring(0, code.length - 1);
                $.operate.remove(url, code, msg, callback);
            },
            // 提示请求
            confirm: function(url, param, msg, callback) {
                msg = msg || '确定执行该操作吗？';
                $.modal.lay.confirm(msg, function() {
                    $.ajax({
                        url: url,
                        // headers: {
                        //     'Authorization': authorization
                        // },
                        data: param,
                        type: 'post',
                        dataType: 'json',
                        beforeSend: function () {
                            $.modal.loading('处理中，请稍后...');
                        },
                        complete: function () {
                            $.modal.closeLoading();
                        },
                        success: function(result) {
                            if (result.code == 200) {
                                $.modal.toast.success(result.msg);
                                if (callback) {
                                    var fn;
                                    if(window.execScript) {
                                        // 给IE的特殊待遇
                                        fn = window.execScript(callback);
                                    } else {
                                        // 给其他大部分浏览器用的
                                        fn = window.eval(callback);
                                    }

                                    if (fn) fn.call(this);
                                }
                            } else {
                                $.modal.toast.error(result.msg, result.param);
                            }
                        },
                        error: function(result) {
                            window.location.href = ctx + '500';
                        }
                    });
                });
            }
        },
        // 图片裁剪处理
        crop: {
            _url: null,
            _uploaded: false,
            _active: false,
            support: {
                $form:  $('#form_avatar'),
                $file: $('#avatar_file'),
                $btn:  $('#form_avatar').find('.avatar-btns'),
                $thumb: $('#form_avatar').find('.avatar-wrapper'),
                $prev: $('#form_avatar').find('.avatar-preview'),
                $avatarSrc: $('#avatar_src'),
                $avatarData: $('#avatar_data'),
                dataUri: null
            },
            init: function (url) {
                if (url) {
                    $.crop.support.$avatarSrc.val(url);
                    $.crop._url = ctx + url;
                    $.crop.startCropper();
                }

                $.crop.support.$file.on('change', $.proxy($.crop.change, this));
                $.crop.support.$btn.not('.form-submit').on('click', $.proxy($.crop.rotate, this));
            },
            change: function() {
                var files = $.crop.support.$file.prop('files');
                if (files.length > 0) {
                    var file = files[0];
                    if ($.crop.isImageFile(file)) {
                        if ($.crop._url) {
                            URL.revokeObjectURL($.crop._url);
                        }
                        $.crop._url = URL.createObjectURL(file);
                        $.crop.startCropper();
                    }
                }
            },
            isImageFile: function (file) {
                if (file.type) {
                    return /^image\/\w+$/.test(file.type);
                } else {
                    return /\.(jpg|jpeg|png|gif)$/.test(file);
                }
            },
            startCropper: function () {
                if ($.crop._active) {
                    $.crop.support.$img.cropper('replace', $.crop._url);
                } else {
                    $.crop.support.$img = $('<img src="' + $.crop._url + '">');
                    $.crop.support.$thumb.empty().html($.crop.support.$img);
                    $.crop.support.$img.cropper({
                        aspectRatio: 1,
                        preview: $.crop.support.$prev.selector,
                        strict: false,
                        crop: function (data) {
                            var json = [
                                '{"x":' + data.x,
                                '"y":' + data.y,
                                '"height":' + data.height,
                                '"width":' + data.width,
                                '"rotate":' + data.rotate + '}'
                            ].join();

                            $.crop.support.$avatarData.val(json);
                        }
                    });

                    $.crop._active = true;
                }
            },
            rotate: function (e) {
                var data;

                if ($.crop._active) {
                    data = $(e.target).data();
                    if (data.method) {
                        $.crop.support.$img.cropper(data.method, data.option);
                    }
                }
            },
            stopCropper: function () {
                if ($.crop._active) {
                    $.crop.support.$img.cropper('destroy');
                    $.crop.support.$img.remove();
                    $.crop._active = false;
                }
            },
            cropDone: function () {
                $.crop.support.$form.get(0).reset();
                $.crop.support.$img.attr('src', $.crop._url);
                $.crop.stopCropper();
            }
        },
        fileInputPlug: {
            _content_type: {
                mp3: 'audio/mp3',
                wav: 'audio/wav',
                ogg: 'audio/ogg',
                rm: 'video/vnd.rn-realmedia',
                rmvb: 'video/vnd.rn-realmedia-vbr',
                avi: 'video/avi',
                mp4: 'video/mp4',
                mpeg: 'video/mpg',
                wmv: 'video/x-ms-wmv'
            },
            _file_type: {
                pdf: 'pdf',
                txt: 'text',
                //xls: 'office',
                //xlsx: 'office',
                //doc: 'office',
                //docx: 'office',
                //ppt: 'office',
                //pptx: 'office',
                //tiff: 'gdocs',
                xls: 'other',
                xlsx: 'other',
                doc: 'other',
                docx: 'other',
                ppt: 'other',
                pptx: 'other',
                tiff: 'other',
                gif: 'image',
                ico: 'image',
                jpg: 'image',
                jpeg: 'image',
                png: 'image',
                bmp: 'image',
                swf: 'flash',
                ogg: 'audio',
                mp3: 'audio',
                wav: 'audio',
                rm: 'video',
                rmvb: 'video',
                avi: 'video',
                mov: 'video',
                mp4: 'video',
                mpeg: 'video',
                wmv: 'video'
            },
            init: function(inputId, files, options, hiddenBottom) {
                hiddenBottom = $.common.isEmpty(hiddenBottom) ? false : true;
                options = $.fileInputPlug.renderFile(files, options, hiddenBottom);

                $('#' + inputId).fileinput(options);
                if (typeof mediaelementplayer !== 'undefined') {
                    // 初始化音视频播放器
                    $('video,audio').mediaelementplayer();
                }
            },
            renderFile: function(files, options, hiddenBottom) {
                var initialPreview = [], initialPreviewConfig = [];
                // 初始化文件
                $.fileInputPlug.initialFiles(files, options, initialPreview, initialPreviewConfig);
                var default_option = {
                    theme: 'explorer',  // 样式fa explorer explorer-fa
                    showUpload: true,   // 是否显示上传按钮
                    showRemove: true,   // 是否显示移除按钮
                    showPreview: true,  //是否显示预览
                    showCaption: true,  //是否显示标题
                    showDownload: true, //是否显示下载按钮
                    showBrowse: true,   //是否显示浏览按钮
                    showClose: false,   //是否显示关闭按钮
                    dropZoneEnabled: false,//是否显示拖拽区域
                    initialPreview: initialPreview,             //初始预览文件
                    initialPreviewConfig: initialPreviewConfig, //初始预览文件配置
                    initialPreviewAsData: true,
                    // ['image', 'html', 'text', 'office', 'gdocs', 'video', 'audio', 'flash', 'object']
                    allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
                    previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
                    previewFileIconSettings: {
                        'doc': '<i class="fa fa-file-word-o text-success"></i>',
                        'docx': '<i class="fa fa-file-word-o text-success"></i>',
                        'xls': '<i class="fa fa-file-excel-o text-primary"></i>',
                        'xlsx': '<i class="fa fa-file-excel-o text-primary"></i>',
                        'ppt': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                        'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                        'jpg': '<i class="fa fa-file-photo-o text-success"></i>',
                        'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>'
                    }
                };
                if ($.common.isNotEmpty(options)) {
                    $.extend(default_option, options);
                }

                if (default_option.showDownload == true && $.common.isEmpty(default_option.initialPreviewDownloadUrl)) {
                    //下载链接
                    default_option.initialPreviewDownloadUrl = ctx + 'public/file/download/{key}';
                }
                if (default_option.showRemove == true && $.common.isEmpty(default_option.deleteUrl)) {
                    //删除链接
                    default_option.deleteUrl = ctx + 'public/file/delete';
                }

                if (hiddenBottom) {
                    default_option.mainClass = 'hidden';
                    default_option.browseClass = 'hidden';
                }

                return default_option;
            },
            initialFiles: function(files, options, initialPreview, initialPreviewConfig) {
                if (files && files.length > 0) {
                    $.each(files, function (index, file) {
                        var config = {
                            caption: file.originalFilename + '(' + file.fileId + ')',
                            filename: file.originalFilename,
                            key: file.fileId,
                            width: 'auto',
                            height: 'auto'
                        };
                        var src = ctx + 'public/file/preview/' + file.fileId;
                        if ($.common.isNotEmpty(options.initialPreviewUrl)) {
                            config.key = file.path;
                            src = encodeURI(options.initialPreviewUrl + '?key=' + file.path);
                        }
                        $.fileInputPlug.checkContentType(file);

                        if (file.channel) {
                            config.type = file.channel;
                            if (file.channel == 'video') {
                                config.filetype = 'video/webm';
                            } else if (file.channel == 'audio') {
                                config.filetype = 'audio/mp3';
                            }
                        }

                        if (file.contentType) {
                            config.filetype = file.contentType;
                        }

                        initialPreview.push(src);
                        initialPreviewConfig.push(config);
                    });
                }
            },
            checkContentType: function(file) {
                var fileType = $.fileInputPlug._file_type[file.contentType];
                var contentType = $.fileInputPlug._content_type[file.contentType];
                file.channel = fileType;
                file.contentType = contentType;
            }
        }
    });

    if (!ctx) {
        ctx = $.common.rootPath();
    }

})(jQuery);
